/**
 * @fileoverview   ajax/request  Ajax核心部分、post，get
 * Created by fu.
 * Date: 12-2-1
 * Time: 上午11:39
 */
F.reg('ajax/request', function (f, ajax, json) {
    var win = window;
    var defaultconfig = ajax.config;
    var parse = function (url, param) {
        url = url || '';
        url += (url.indexOf('?') == -1 ? '?' : '&');
        if (f.type(param, 'string')) {
            url += param;
        } else {
            f.each(param || {}, function (val, key) {
                url += encodeURIComponent(key) + '=' + encodeURIComponent(val) + '&';
            });
        }
        return url;
    };

    function setupXHR(type, url, arg, fn) {
        var config = {}, jsonpCallback = 'jsonp_';

        //处理参数
        if (f.type(fn, 'function')) {
            config.success = fn;
            config.param = arg;
            config.url = url;
        } else if (f.type(arg, 'object')) {
            config.param = arg;
            config.url = url;
        } else if (f.type(arg, 'function')) {
            config.success = arg;
            config.url = url;
        } else if (f.type(url, 'object')) {
            config = url;
        }
        config = f.merge(defaultconfig, config);
        // jsonp ?
        if (config.dataType === 'jsonp') {

            if (config.jsonpCallback === '') {
                jsonpCallback += new Date().getTime();
                config.jsonpCallback = jsonpCallback;
            }

            config.url = config.url.replace(/(\?)$/, config.jsonpCallback);
            f.load([config.url]);
            win[config.jsonpCallback] = function (data) {
                config.success(data);
            };
            return;
        }

        var xhr = ajax.createXHR();

        xhr.onreadystatechange = function () {
            var headers, data;
            try {
                if (xhr.readyState == 2) {
                    //开始
                    config.start(xhr);
                } else if (xhr.readyState == 4) {


                    //完成
                    config.complete(xhr);

                    if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
                        //成功
                        headers = xhr.getAllResponseHeaders().match(/Content-Type: .*/)[0];

                        if (headers.indexOf('json') > -1) {
                            data = json.parse(xhr.responseText);
                        } else if (headers.indexOf('html') > -1) {
                            data = xhr.responseText;
                        } else if (headers.indexOf('text') > -1) {
                            data = xhr.responseText;
                        } else if (headers.indexOf('xml') > -1) {
                            data = xhr.responseXML;
                        }


                        config.success(data, xhr);
                    } else {
                        //错误
                        config.error(xhr);
                    }
                }


            } catch (e) {

            }
        };


        switch (type) {
            case 'get':
            {

                xhr.open('get', parse(config.url, config.param), true);
                xhr.send(null);
                break;
            }
            case 'post':
            {
                xhr.open('post', config.url, true);
                xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                xhr.send(parse(config.param));
                break;
            }
        }
    }

    ajax = f.merge(ajax, {
        /**
         * @name F.Ajax.get
         * @function
         * @param url
         * @param arg
         * @param fn
         * @namespace get 请求
         * @example
         * 例子：
         * 1.
         *   ajax.get({
         *       url:'http://192.168.0.110/f/php/?call=?',
         *       dataType:'jsonp',
         *       error:function(xhr){
         *           f.log('error');
         *       },
         *
         *       success:function(data,xhr){
         *
         *       },
         *       start:function(){
         *       },
         *       complete:function(){
         *       }
         *
         *   });
         *2.
         * ajax.get('aa.php',function(data){
         *     consolse.log(data);
         * });
         *
         */
        get:function (url, arg, fn) {
            setupXHR('get', url, arg, fn);
        },
        /**
         * @name F.Ajax.post
         * @function
         * @param url
         * @param arg
         * @param fn
         * @namespace post 请求
         * @example
         * 1.
         *   ajax.post({
         *       url:'http://192.168.0.110/f/php/?call=?',
         *       dataType:'jsonp',
         *       error:function(xhr){
         *           f.log('error');
         *       },
         *
         *       success:function(data,xhr){
         *
         *       },
         *       start:function(){
         *       },
         *       complete:function(){
         *       }
         *
         *   });
         *2.
         * ajax.post('aa.php',function(data){
         *     consolse.log(data);
         * });
         *

         */
        post:function (url, arg, fn) {
            setupXHR('post', url, arg, fn);
        }
    });
    return ajax;
}, {
    requires:[
        'json'
    ]
});